package com.ysyx.ysyx_jwt.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Calendar;
import java.util.Map;

public class JwtUtils {
    private  static  final String  SECRET_KEY="654321";

    //生成令牌
    public static  String createToken(Map<String,String> payload){
        JWTCreator.Builder builder= JWT.create();
        payload.forEach((name,value)->{
            builder.withClaim(name,value);
        });

        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
       builder.withExpiresAt(calendar.getTime());
       builder.withSubject("com.cyzy");



        return builder.sign(Algorithm.HMAC256(SECRET_KEY));
    }

//    解签
public static DecodedJWT decodedJWT(String token){ //验签
    JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build();
    DecodedJWT decodedJWT = verifier.verify(token);
    return decodedJWT;
}



    public static String getClaim(String token ,String name){ //获取身份
        String claim = null;
        try {
            claim = JWT.decode(token).getClaim(name).asString();
        }catch (JWTDecodeException e){
            return "getClaim False";
        }
        return claim;
    }







}
